from rest_framework import serializers
from .models import FlowerCategory, Flower, FlowerImage, FlowerSpec


class FlowerImageSerializer(serializers.ModelSerializer):
    """鲜花图片序列化器"""
    
    class Meta:
        model = FlowerImage
        fields = ['id', 'image_url', 'is_main', 'sort_order']


class FlowerSpecSerializer(serializers.ModelSerializer):
    """鲜花规格序列化器"""
    
    class Meta:
        model = FlowerSpec
        fields = ['id', 'name', 'price', 'stock', 'is_active', 'sort_order']


class FlowerCategorySerializer(serializers.ModelSerializer):
    """鲜花分类序列化器"""
    
    class Meta:
        model = FlowerCategory
        fields = ['id', 'name', 'description', 'image', 'sort_order', 'is_active']


class FlowerListSerializer(serializers.ModelSerializer):
    """鲜花列表序列化器"""
    category_name = serializers.CharField(source='category.name', read_only=True)
    main_image = serializers.SerializerMethodField()
    
    class Meta:
        model = Flower
        fields = [
            'id', 'name', 'category_name', 'price', 'original_price', 
            'stock', 'sales_count', 'status', 'is_featured', 'main_image'
        ]
    
    def get_main_image(self, obj):
        """获取主图URL"""
        main_image = obj.images.filter(is_main=True).first()
        if main_image:
            return main_image.image_url
        # 如果没有主图，返回第一张图片
        first_image = obj.images.first()
        return first_image.image_url if first_image else None


class FlowerDetailSerializer(serializers.ModelSerializer):
    """鲜花详情序列化器"""
    category = FlowerCategorySerializer(read_only=True)
    images = FlowerImageSerializer(many=True, read_only=True)
    specs = FlowerSpecSerializer(many=True, read_only=True)
    
    class Meta:
        model = Flower
        fields = [
            'id', 'name', 'category', 'description', 'price', 'original_price',
            'stock', 'sales_count', 'status', 'is_featured', 'images', 'specs',
            'created_at', 'updated_at'
        ]


class FlowerCreateUpdateSerializer(serializers.ModelSerializer):
    """鲜花创建/更新序列化器"""
    images = FlowerImageSerializer(many=True, required=False)
    specs = FlowerSpecSerializer(many=True, required=False)
    
    class Meta:
        model = Flower
        fields = [
            'name', 'category', 'description', 'price', 'original_price',
            'stock', 'status', 'sort_order', 'is_featured', 'images', 'specs'
        ]
    
    def create(self, validated_data):
        images_data = validated_data.pop('images', [])
        specs_data = validated_data.pop('specs', [])
        
        flower = Flower.objects.create(**validated_data)
        
        # 创建图片
        for image_data in images_data:
            FlowerImage.objects.create(flower=flower, **image_data)
        
        # 创建规格
        for spec_data in specs_data:
            FlowerSpec.objects.create(flower=flower, **spec_data)
        
        return flower
    
    def update(self, instance, validated_data):
        images_data = validated_data.pop('images', None)
        specs_data = validated_data.pop('specs', None)
        
        # 更新基本信息
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()
        
        # 更新图片
        if images_data is not None:
            instance.images.all().delete()
            for image_data in images_data:
                FlowerImage.objects.create(flower=instance, **image_data)
        
        # 更新规格
        if specs_data is not None:
            instance.specs.all().delete()
            for spec_data in specs_data:
                FlowerSpec.objects.create(flower=instance, **spec_data)
        
        return instance


class ImageUploadSerializer(serializers.Serializer):
    """图片上传序列化器"""
    image = serializers.ImageField()
    
    def validate_image(self, value):
        # 验证文件大小（5MB）
        if value.size > 5 * 1024 * 1024:
            raise serializers.ValidationError("图片大小不能超过5MB")
        
        # 验证文件格式
        allowed_formats = ['JPEG', 'PNG', 'GIF', 'WEBP']
        if hasattr(value, 'image') and value.image.format not in allowed_formats:
            raise serializers.ValidationError("不支持的图片格式")
        
        return value